#include"mySql.h"
#include"threadpool.h"

//连接数据库
MYSQL * connectMysql(){
    printf("try enter mysql...\n");
    MYSQL* mysql = NULL;//和mysql交互的对象
    mysql = mysql_init(NULL);
    if(mysql==NULL){
        printf("mysql_inin:%s\n", mysql_error(mysql));
    }
    mysql = mysql_real_connect(mysql,"localhost",
                               "root","123456",
                               "wangpan",3306,NULL,0);
    if(mysql == NULL){
        printf("connect error\n");
        mysql_error(mysql);
    }else{
        printf("connect\n");
    }
    return mysql;
}

//生成sale
void  GenerateStr(char* str){
    int i,flag;
    srand(time(NULL));

    for(i = 0;i<STR_LEN;i++){
        flag = rand() % 3;
        switch(flag){
        case 0:str[i]=rand()%26+'a';break;
        case 1:str[i]=rand()%26+'A';break;
        case 3:str[i]=rand()%26+'0';break;
        default: str[i] = 'x'; break;
        }
    }
    printf("generateStr is %s\n",str);
    return;

}

//语句执行
int handlQuery(MYSQL*mysql,char*query,int peerfd){
    int ret = mysql_query(mysql,query);
    printf("--/*handlQuery*/-- is:%s\n",query);
    if(ret != 0){
        char a[1000]={0};
        sprintf(a,"handlQuery: %s",mysql_error(mysql));
        printf("error query : %s\n",mysql_error(mysql));
        trainSend(a,peerfd);
    }
    return ret;
}
//语句执行,要与客户端进行交互
void handlQueryClient(MYSQL*mysql,char*query,int peerfd){
    int ret = mysql_query(mysql,query);
    printf("--/*handlQuery*/-- is:%s\n",query);
    if(ret != 0){
        char a[1000]={0};
        sprintf(a,"error query:%s",mysql_error(mysql));
        printf("error query : %s\n",mysql_error(mysql));
        //将错误信息发送给客户端
        trainSend(a,peerfd);
    }
    //执行成功发送1
    char b[2]="1";
    trainSend(b,peerfd);
    return;
}

//打印表
void printTable(MYSQL*mysql,char* name,int peerfd){
    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据

    int num_fields;//保存列数
    printf("enter printTable\n");
    char query[1024] = {0};
    sprintf(query,"select * from %s;",name);
    printf("printTable query is: %s\n",query);
    handlQuery(mysql,query,peerfd);

    res = mysql_store_result(mysql);//获取结果
    printf("enter printTable res\n");
    num_fields = mysql_num_fields(res);//获取结果列数
    printf("enter printTable  num_fields\n");

    while((row = mysql_fetch_row(res))!=NULL){
        for(int i = 0;i<num_fields;i++){
            char* tmp = row[i];
            printf("%s ",tmp);
        }
        printf("\n");
    }
    // return;
}

void recvSaltCryptpasswd(MYSQL*mysql,char*salt,char*cryptpasswd,
                         char*name,char*id,int peerfd){
    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据
    int num_fields;//保存列数
    //mysql = connectMysql();

    char query[100]={0};
    sprintf(query,"select salt,cryptpasswd,id from user where username = '%s';",name);
    printf("query is: %s\n",query);
    handlQuery(mysql,query,peerfd);

    printf("handlQuery is success\n");

    res = mysql_store_result(mysql);//获取结果
    printf("res is success\n");
    num_fields = mysql_num_fields(res);//获取结果列数
    printf("num_fields is success\n");

    row = mysql_fetch_row(res);
    strcpy(salt,row[0]);
    printf("salt:%s\n",salt);

    strcpy(cryptpasswd,row[1]);
    printf("cryptpasswd:%s\n",cryptpasswd);

    strcpy(id,row[2]);
    printf("id:%s\n",id);
}

void userRegister(MYSQL*mysql,int peerfd,char*id){
    printf("---enter userRegister\n");
    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据

    char salt[100]={0};
    char cryptpasswd[100]={0};
    char query[100]={0};
    char name[1024]={0};
    char passwd[10]={0};//键盘上输入的密码
    char username[20]={0};//键盘上输入的名字去掉\n

    //输入名字
    trainRecv(name,peerfd);
    trainRecv(passwd,peerfd);
    printf("--register name:%s\n",name);
    printf("passwd is %s\n",passwd);

    memcpy(username,name,strlen(name)-1);//去掉名字里面的\n
    //printf("--register username:%s\n",username);

    GenerateStr(salt);//生成盐值
    //printf("--register salt is %s\n",salt);
    //printf("%s\n",crypt(passwd,salt));

    char* pwd = getcwd(NULL,0);//获取当前工作目录
    //printf("--register pwd is %s\n",pwd);

    //printf("--register icrypt:%s",crypt(passwd,salt));

    strcpy(cryptpasswd,crypt(passwd,salt));//生成密文
    //printf("--register cryptpasswd is :%s\n",cryptpasswd);

    //用户注册
    strcpy(query,"select * from user");
    printf("注册查询的query is %s\n",query);

    handlQuery(mysql,query,peerfd);
    res = mysql_store_result(mysql);//获取结果

    //判断是否为空表
    if((row = mysql_fetch_row(res))==NULL){//是空表
        memset(&query,0,sizeof(query));
        sprintf(query,"insert into user values(1,'%s' , '%s' , '%s','%s');",
                username,salt,cryptpasswd,pwd);
        handlQueryClient(mysql,query,peerfd);
        char sqlSalt[100]={0};
        char sqlCryptpasswd[100]={0};
        //找出username的id
        recvSaltCryptpasswd(mysql,sqlSalt,
                            sqlCryptpasswd,username,id,peerfd);
        //创建对应用户的虚拟文件表
        createTable(mysql,username,id,peerfd);
        char tablename[10]="user";
        printTable(mysql,tablename,peerfd);//注册成功后打印该表    
    }else{//不是空表
        memset(&query,0,sizeof(query));
        sprintf(query,"insert into user(username,salt,cryptpasswd,pwd) values('%s','%s','%s','%s');",
                username,salt,cryptpasswd,pwd);
        printf("--query is :%s\n",query);

        handlQueryClient(mysql,query,peerfd);
        char sqlSalt[100]={0};
        char sqlCryptpasswd[100]={0};
        //找出username的id
        recvSaltCryptpasswd(mysql,sqlSalt,
                            sqlCryptpasswd,username,id,peerfd);

        //创建对应用户的虚拟文件表
        createTable(mysql,username,id,peerfd);
        char tablename[10]="user";
        printTable(mysql,tablename,peerfd);//注册成功后打印该表
    }
}

//创建用户对应的虚拟文件表
void createTable(MYSQL*mysql,char*username,char*id,int peerfd){
    char query[1000]={0};
    //sprintf(query,"create table %s( id int auto_increment, parent_id int, filename varchar(20) unique, owner_id int, md5 char(100), filesize int, type char, primary key(id));",username);

    //创建username专属的虚拟表
    sprintf(query,"create table %s( id int auto_increment, parent_id int, filename varchar(20), owner_id int, md5 char(100), filesize int, type char, foreign key(owner_id) references user(id), primary key(id));",username);
    printf("--createTable query is:%s\n",query);
    handlQuery(mysql,query,peerfd);

    //初始化username虚拟表
    //memset(&query,0,sizeof(query));
    //int userid = atoi(id);
    //sprintf(query,"insert into %s values(1,0 , 'serverFile' , %d, '0', 0, 'd');",username,userid);
    //handlQuery(mysql,query);

    //将username的信息放到server虚拟表上
    // memset(&query,0,sizeof(query));
    // sprintf(query,"insert into server values(1,0 , 'serverFile' , %d, '0', 0, 'd');",userid);
    // handlQuery(mysql,query);

    //这串代码没效果，不用管
    memset(&query,0,sizeof(query));
    sprintf(query,"alter table %s auto_increment = 1;",username);
    printf("--createTable query-- is:%s\n",query);
    handlQuery(mysql,query,peerfd);
}

void insertTable(MYSQL*mysql,char*username,
                 int parent_id,char*filename,
                 int owner_id,char*md5,int filesize,
                 char*type,int peerfd){

    char query[1000]={0};
    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据

    //插入到用户对应的虚拟表
    sprintf(query,"select * from %s",username);
    printf("insertTable query is: %s\n",query);

    handlQuery(mysql,query,peerfd);
    res = mysql_store_result(mysql);//获取结果

    //判断是否为空表
    if((row = mysql_fetch_row(res))==NULL){//是空表
        memset(&query,0,sizeof(query));
        sprintf(query,"insert into %s values(1, %d, '%s', %d, '%s', %d, '%s');",
                username,parent_id,filename,owner_id,md5,filesize,type); 
        printf("--insertTable query is:%s",query);
        int ret = handlQuery(mysql,query,peerfd);
        if(ret!=0){
            return;
        }
    }else{
        memset(&query,0,sizeof(query));
        sprintf(query,"select filename from %s where parent_id = %d and owner_id = %d and filename = '%s';",
                username,parent_id,owner_id,filename);
        handlQuery(mysql,query,peerfd);
        MYSQL_RES *res1;//SQL执行结果
        MYSQL_ROW row1;//保存行数据
        res1 = mysql_store_result(mysql);//获取结果
        //若存在此数据则不插入
        if((row1 = mysql_fetch_row(res1))!=NULL){
            return;
        }else{
            memset(&query,0,sizeof(query));
            sprintf(query,"insert into %s(parent_id,filename,owner_id,md5,filesize,type) values(%d, '%s', %d, '%s', %d, '%s');",
                    username,parent_id,filename,owner_id,md5,filesize,type); 
            printf("--insertTable query is:%s",query);
            int ret = handlQuery(mysql,query,peerfd);
            if(ret!=0){
                return;
            }
        }
    }

    //插入到服务器存储所有文件的虚拟表
    memset(query,0,sizeof(query));
    strcpy(query,"select * from server");
    printf("insertTable server query is: %s\n",query);

    handlQuery(mysql,query,peerfd);
    res = mysql_store_result(mysql);//获取结果

    //判断是否为空表
    if((row = mysql_fetch_row(res))==NULL){//是空表
        memset(&query,0,sizeof(query));
        sprintf(query,"insert into server values(1, %d, '%s', %d, '%s', %d, '%s');",
                parent_id,filename,owner_id,md5,filesize,type); 
        printf("--insertTable server query is:%s",query);
        handlQuery(mysql,query,peerfd);
    }else{
        /*memset(&query,0,sizeof(query));
        sprintf(query,"select filename from server where parent_id = %d and owner_id = %d;",
                parent_id,owner_id);
        handlQuery(mysql,query);
        MYSQL_RES *res1;//SQL执行结果
        MYSQL_ROW row1;//保存行数据
        res1 = mysql_store_result(mysql);//获取结果
        //若存在此数据则不插入
        if((row1=mysql_fetch_row(res1))!=NULL){
            return;
        }else{*/
            memset(&query,0,sizeof(query));
            sprintf(query,"insert into server(parent_id,filename,owner_id,md5,filesize,type) values(%d, '%s', %d, '%s', %d, '%s');",
                    parent_id,filename,owner_id,md5,filesize,type); 
            printf("--insertTable server query is:%s",query);
            handlQuery(mysql,query,peerfd);
    }
}

//void delTable(MYSQL*mysql,char*username,char*filename,
//              char*md5,int owner_id,int peerfd){
//
//}
